/**
 * Avatar crop
 */

$(document).ready(function(){
});

var ratio = 150/150;
var jcrop_api;


function onClickMakeAvatar(area, id) {
	var id_img = typeof id != 'undefined' 
		? id 
		: typeof $('#id_see_img'+area) != 'undefined' 
			? 'id_see_img'+area 
			: typeof $('#fancybox-img') != 'undefined' 
				? 'fancybox-img' 
				: '';
	if ( id_img == '' ) return false;
	cropboxLoad(area, id_img);
	$('#id_see_avatar_make'+area).hide();
	$('#id_see_avatar_save'+area).show();
	$('#id_see_avatar_cancel'+area).show();
	return false;
}

function onClickSaveAvatar(area) {
	if ( checkCoords(area) )
		$('#id_saveAvatar_submit'+area).click();
	$.fancybox.close();
	//$('#sd_closelabel img').click();
	return false;
}

function onClickCancelAvatar(area)
{
	if (typeof jcrop_api != 'undefined'){
		destroyCrop(area);
	}
	$('#id_see_avatar_make'+area).show();
	$('#id_see_avatar_save'+area).hide();
	$('#id_see_avatar_cancel'+area).hide();
	return false;
}


function initJcrop(area, idBox) {
	jcrop_api = $.Jcrop('#'+idBox);
	jcrop_api.setOptions({
		aspectRatio: ratio,
		minSize: [150,150],
		onSelect: function (c) {updateCoords(area, c)}
	});
}

function cropboxLoad(area, idBox) {
	initJcrop(area, idBox);
	setSelection(area);
	return false;
}

function setSelection(area) {
	var dim = jcrop_api.getBounds();
	if (dim[0]/dim[1] > ratio) {
		var xc = dim[0]/2,
			w2 = dim[1]*ratio/2;
		jcrop_api.setSelect([Math.round(xc-w2), 0, Math.round(xc+w2), dim[1]]);
		jQuery('#id_saveAvatar_x'+area).val(Math.round(xc-w2));
		jQuery('#id_saveAvatar_y'+area).val(0);
		jQuery('#id_saveAvatar_w'+area).val(Math.round(xc+w2));
		jQuery('#id_saveAvatar_h'+area).val(dim[1]);
	} else {
		var yc = dim[1]/2,
			h2 = dim[0]/(ratio*2);
		jcrop_api.setSelect([0, Math.round(yc-h2), dim[0], Math.round(yc+h2)]);
		jQuery('#id_saveAvatar_x'+area).val(0);
		jQuery('#id_saveAvatar_y'+area).val(Math.round(yc-h2));
		jQuery('#id_saveAvatar_w'+area).val(dim[0]);
		jQuery('#id_saveAvatar_h'+area).val(Math.round(yc+h2));
	}
}

function updateCoords(area,c) {
	jQuery('#id_saveAvatar_x'+area).val(c.x);
	jQuery('#id_saveAvatar_y'+area).val(c.y);
	jQuery('#id_saveAvatar_w'+area).val(c.w);
	jQuery('#id_saveAvatar_h'+area).val(c.h);
}

function checkCoords(area) {
	if (parseInt(jQuery('#id_saveAvatar_w'+area).val())>0) return true;
	$.fancybox({
		'content': '<div class="form form-mw">'+Dictionary.translate('lang_photostudio_crop_select_region')+'</div>',
	});
	//alert(Dictionary.translate('lang_photostudio_crop_select_region'));
	//alert('Please select a crop region then press submit.');
	return false;
}

function destroyCrop(area) {
	jcrop_api.destroy();
	return false;
}

//$(window).load(cropboxLoad());
